/**
 * MACAddressValidator.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年5月18日
 */
package com.pshare.artemis.framework.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.pshare.artemis.common.constant.ReturnMsg;
import com.pshare.artemis.framework.annotation.SnCodeCheck;

/**
 * 蓝牙锁编号格式验证
 */
public class SnCodeValidator implements ConstraintValidator<SnCodeCheck, CharSequence> {

	private static String REGEX = "(\\d{13})";

	private static Pattern pattern = Pattern.compile(REGEX);

	@Override
	public void initialize(SnCodeCheck constraintAnnotation) {
		
	}

	@Override
	public boolean isValid(CharSequence object, ConstraintValidatorContext constraintContext) {
		if (StringUtils.isBlank(object ))
			return true;

		String input = object.toString().trim();
		boolean valid = false;
		Matcher matcher = pattern.matcher(input);
		if (matcher.matches()) {
			valid = true;
		}

        if(!valid) {
            constraintContext.disableDefaultConstraintViolation();
            constraintContext.buildConstraintViolationWithTemplate(ReturnMsg.SN_CODE_FORMAT).addConstraintViolation();
        }
        
        return valid;
	}

}
